# -*- coding: utf-8 -*-
"""
Base Configuration Settings

This module defines the base configuration settings shared across all environments.
"""

from typing import List, Dict, Any
from pydantic import Field

try:
    from pydantic_settings import BaseSettings as PydanticBaseSettings
except ImportError:
    from pydantic import BaseSettings as PydanticBaseSettings


class BaseSettings(PydanticBaseSettings):
    """
    Base configuration settings
    
    All environment-specific settings should inherit from this class.
    """
    
    # Service Basic Info
    service_name: str = Field(
        default="market-data-service",
        description="Service name"
    )
    service_version: str = Field(
        default="2.0.0",
        description="Service version"
    )
    environment: str = Field(
        default="development",
        description="Environment (development/production/testing)"
    )
    
    # API Configuration
    api_host: str = Field(
        default="0.0.0.0",
        description="API host to bind"
    )
    api_port: int = Field(
        default=8004,
        description="API port"
    )
    api_prefix: str = Field(
        default="/api/v1",
        description="API route prefix"
    )
    
    # CORS Configuration
    cors_origins: List[str] = Field(
        default=["*"],
        description="Allowed CORS origins"
    )
    cors_credentials: bool = Field(
        default=True,
        description="Allow credentials in CORS"
    )
    cors_methods: List[str] = Field(
        default=["*"],
        description="Allowed CORS methods"
    )
    cors_headers: List[str] = Field(
        default=["*"],
        description="Allowed CORS headers"
    )
    
    # Database Configuration
    influxdb_url: str = Field(
        default="http://localhost:8086",
        description="InfluxDB URL"
    )
    influxdb_token: str = Field(
        default="",
        description="InfluxDB authentication token"
    )
    influxdb_org: str = Field(
        default="redfire_org",
        description="InfluxDB organization"
    )
    influxdb_bucket: str = Field(
        default="redfire_bucket",
        description="InfluxDB bucket name"
    )
    
    # Redis Configuration
    redis_host: str = Field(
        default="localhost",
        description="Redis host"
    )
    redis_port: int = Field(
        default=6379,
        description="Redis port"
    )
    redis_password: str = Field(
        default="",
        description="Redis password"
    )
    redis_db: int = Field(
        default=0,
        description="Redis database number"
    )
    
    # Cache Configuration
    cache_default_ttl: int = Field(
        default=3600,
        description="Default cache TTL in seconds"
    )
    cache_max_size: int = Field(
        default=1000,
        description="Maximum cache size"
    )
    
    # L1 Cache (Memory)
    cache_l1_enabled: bool = Field(
        default=True,
        description="Enable L1 memory cache"
    )
    cache_l1_max_size: int = Field(
        default=100,
        description="L1 cache max size"
    )
    cache_l1_ttl: int = Field(
        default=300,
        description="L1 cache TTL in seconds"
    )
    
    # L2 Cache (Redis)
    cache_l2_enabled: bool = Field(
        default=True,
        description="Enable L2 Redis cache"
    )
    cache_l2_ttl: int = Field(
        default=1800,
        description="L2 cache TTL in seconds"
    )
    cache_l2_prefix: str = Field(
        default="market_data:",
        description="L2 cache key prefix"
    )
    
    # L3 Cache (Database)
    cache_l3_enabled: bool = Field(
        default=True,
        description="Enable L3 database cache"
    )
    cache_l3_ttl: int = Field(
        default=3600,
        description="L3 cache TTL in seconds"
    )
    
    # Router Configuration
    router_enabled: bool = Field(
        default=True,
        description="Enable data source router"
    )
    router_auto_failover: bool = Field(
        default=True,
        description="Enable automatic failover"
    )
    router_max_failover_attempts: int = Field(
        default=3,
        description="Maximum failover attempts"
    )
    router_default_priority: List[str] = Field(
        default=["tushare", "akshare", "influxdb"],
        description="Default adapter priority list"
    )
    
    # Resilience Configuration
    resilience_circuit_breaker_enabled: bool = Field(
        default=True,
        description="Enable circuit breaker"
    )
    resilience_cb_failure_threshold: int = Field(
        default=5,
        description="Circuit breaker failure threshold"
    )
    resilience_cb_success_threshold: int = Field(
        default=2,
        description="Circuit breaker success threshold"
    )
    resilience_cb_timeout: float = Field(
        default=60.0,
        description="Circuit breaker timeout in seconds"
    )
    
    resilience_rate_limiter_enabled: bool = Field(
        default=True,
        description="Enable rate limiter"
    )
    resilience_rate_limit_requests: int = Field(
        default=100,
        description="Max requests per window"
    )
    resilience_rate_limit_window: float = Field(
        default=60.0,
        description="Rate limit window in seconds"
    )
    
    resilience_retry_enabled: bool = Field(
        default=True,
        description="Enable retry mechanism"
    )
    resilience_retry_max_attempts: int = Field(
        default=3,
        description="Maximum retry attempts"
    )
    resilience_retry_base_delay: float = Field(
        default=1.0,
        description="Base delay for exponential backoff"
    )
    resilience_retry_max_delay: float = Field(
        default=60.0,
        description="Maximum retry delay"
    )
    
    resilience_default_timeout: float = Field(
        default=30.0,
        description="Default operation timeout"
    )
    
    # Monitoring Configuration
    monitoring_enabled: bool = Field(
        default=True,
        description="Enable health monitoring"
    )
    monitoring_check_interval: float = Field(
        default=60.0,
        description="Health check interval in seconds"
    )
    monitoring_unhealthy_threshold: int = Field(
        default=3,
        description="Consecutive failures to mark unhealthy"
    )
    monitoring_enable_metrics: bool = Field(
        default=True,
        description="Enable metrics collection"
    )
    monitoring_metrics_interval: float = Field(
        default=30.0,
        description="Metrics collection interval"
    )
    
    # Data Processing Configuration
    batch_size: int = Field(
        default=1000,
        description="Data batch size"
    )
    max_concurrent_requests: int = Field(
        default=10,
        description="Max concurrent requests"
    )
    data_retention_days: int = Field(
        default=365,
        description="Data retention period in days"
    )
    
    # Real-time Data Configuration
    realtime_enabled: bool = Field(
        default=True,
        description="Enable real-time data"
    )
    websocket_heartbeat_interval: int = Field(
        default=30,
        description="WebSocket heartbeat interval in seconds"
    )
    
    # Performance Configuration
    enable_async_processing: bool = Field(
        default=True,
        description="Enable async processing"
    )
    worker_pool_size: int = Field(
        default=4,
        description="Worker pool size"
    )
    
    # Logging Configuration
    log_level: str = Field(
        default="INFO",
        description="Logging level"
    )
    log_format: str = Field(
        default="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
        description="Log format"
    )
    log_file: str = Field(
        default="logs/market_data_service.log",
        description="Log file path"
    )
    
    @property
    def redis_url(self) -> str:
        """Build Redis connection URL"""
        password_part = f":{self.redis_password}@" if self.redis_password else ""
        return f"redis://{password_part}{self.redis_host}:{self.redis_port}/{self.redis_db}"
    
    @property
    def database_config(self) -> Dict[str, Any]:
        """Get database configuration"""
        return {
            "influxdb": {
                "url": self.influxdb_url,
                "token": self.influxdb_token,
                "org": self.influxdb_org,
                "bucket": self.influxdb_bucket,
            },
            "redis": {
                "host": self.redis_host,
                "port": self.redis_port,
                "password": self.redis_password,
                "db": self.redis_db,
                "url": self.redis_url,
            }
        }
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = False
        extra = "ignore"

